<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/6/11
 * Time: 上午11:24
 */

namespace app\apitemp\controller;


use app\common\model\Agent;
use app\common\model\CardMember;
use app\common\model\CardQrcode;
use app\common\model\DeviceCodeQuery;
use app\common\model\DeviceMicro;
use app\common\model\LoginChange;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use think\Config;
use think\Validate;

class Login extends Pub
{
    public function login($param)
    {
        try {
            $validate = new Validate([
                'username|用户名' => 'require',
                'password|密码' => 'require',
            ]);
            if (!$validate->check($param)) {
                $sdata = array('result_code' => 'FAIL', 'result_msg' => $validate->getError());
            } else {
                $User = new LoginUsers();
                $user = $User->where('username', $param['username'])->find();
                if ($user) {
                    if ($user['password'] == MD5($param['password']) && ($user['level'] == "3001" || $user['level'] == "3002" || $user['level'] == "3003")) {
                        switch ($user['level']) {
                            case "3001":
                                $role = '商户管理员';
                                break;
                            case "3002":
                                $role = '商户店长';
                                break;
                            case "3003":
                                $role = '收银员';
                                break;
                        }
                        if ($user['level'] == "3001") {
                            $Merchant = new Merchant();
                            $midlist = $Merchant->where('top_mid', $user['top_mid'])->field('id')->select();
                            $midarr = [];
                            foreach ($midlist as $k => $v) {
                                $midarr[] = $v['id'];
                            }
                            $mid = implode(',', $midarr);
                            $sdata = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "SUCCESS", "result_msg" => "登录成功", "info" => ["level" => $role, "xingming" => $user['xingming'], "username" => $user['username'], "merchantid" => $mid],);
                        } else {
                            $sdata = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "SUCCESS", "result_msg" => "登录成功", "info" => ["info" => $role, "xingming" => $user['xingming'], "username" => $user['username'], "merchantid" => $user['mid']],);
                        }
                    } else {
                        $sdata = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "FAIL", "result_msg" => "账号密码错误",);
                    }
                } else {
                    $sdata = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "FAIL", "result_msg" => "账号密码错误",);
                }


            }

        } catch (\Exception $e) {
            $sdata = array("return_code" => "FAIL", "return_msg" => "系统错误", "result_code" => "FAIL", "result_msg" => $e->getMessage());
        }
        return $sdata;

    }

    public function privatelogin($param)
    {
        try {
            $validate = new Validate([
                'username|用户名' => 'require',
                'password|密码' => 'require',
            ]);
            if (!$validate->check($param)) {
                $sdata = array('result_code' => 'FAIL', 'result_msg' => $validate->getError());
            } else {
                $User = new LoginUsers();
                $user = $User->where('username', $param['username'])->find();


                if ($user) {
                    if ($user['password'] == MD5($param['password']) && ($user['level'] == "3001" || $user['level'] == "3002" || $user['level'] == "3003")) {
                        if ($user['mid']) {
                            $mae['id'] = $user['mid'];
                        } elseif ($user['top_mid']) {
                            $mae['top_mid'] = $user['top_mid'];
                        }
                        $Merchant = new Merchant();
                        $mchinfo = $Merchant->where($mae)->find();
                        $queryinfo = $this->checkuser($mchinfo['agent'], $param['device_id'], $mchinfo['top_mid']);
                        if ($queryinfo['result_code'] == "SUCCESS") {
                            $Agent = new Agent();
                            $appinfo = $Agent->where('id', $mchinfo['agent'])->field('sign_appid,sign_key')->find();


                            switch ($user['level']) {
                                case "3001":
                                    $role = '商户管理员';
                                    break;
                                case "3002":
                                    $role = '商户店长';
                                    break;
                                case "3003":
                                    $role = '收银员';
                                    break;
                            }
                            if ($user['level'] == "3001") {

                                $midlist = $Merchant->where('top_mid', $user['top_mid'])->field('id')->select();
                                $midarr = [];
                                foreach ($midlist as $k => $v) {
                                    $midarr[] = $v['id'];
                                }
                                $mid = implode(',', $midarr);
                                $sdata = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "SUCCESS", "result_msg" => "登录成功", "info" => ["appid" => $appinfo['sign_appid'], "appkey" => $appinfo['sign_key'], "level" => $role, "xingming" => $user['xingming'], "username" => $user['username'], "merchantid" => $mid],);
                            } else {
                                $sdata = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "SUCCESS", "result_msg" => "登录成功", "info" => ["appid" => $appinfo['sign_appid'], "appkey" => $appinfo['sign_key'], "info" => $role, "xingming" => $user['xingming'], "username" => $user['username'], "merchantid" => $user['mid']],);
                            }
                        } else {
                            $sdata = $queryinfo;
                        }
                    } else {
                        $sdata = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "FAIL", "result_msg" => "账号密码错误",);
                    }
                } else {
                    $sdata = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "FAIL", "result_msg" => "账号密码错误",);
                }


            }

        } catch (\Exception $e) {
            $sdata = array("return_code" => "FAIL", "return_msg" => "系统错误", "result_code" => "FAIL", "result_msg" => $e->getMessage());
        }
        return $sdata;

    }

    private function checkuser($agentid, $code, $top_mid)
    {
        if (empty($agentid) || empty($top_mid)) {
            $re_param = array("return_code" => "SUCCESS", "return_msg" => "商户信息不存在或者不完整", "result_code" => "FAIL", "result_msg" => "商户信息不存在或者不完整");

        } else {
            $DeviceCodeQuery = new DeviceCodeQuery();
            $map['top_mid'] = $top_mid;
            $map['agentid'] = $agentid;
            $map['code'] = $code;
            $info = $DeviceCodeQuery->where($map)->find();
            if (!$info) {
                $s_data['top_mid'] = $top_mid;
                $s_data['agentid'] = $agentid;
                $s_data['code'] = $code;
                $s_data['status'] = 1;
                $s_data['addtime'] = time();
                $DeviceCodeQuery->save($s_data);
                $re_param = array("return_code" => "SUCCESS", "return_msg" => "等待服务商确认", "result_code" => "FAIL", "result_msg" => "等待服务商确认");
            } else {
                if ($info['status'] == 2) {
                    $re_param = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "SUCCESS", "result_msg" => "确认成功");

                } elseif ($info['status'] == 1) {
                    $re_param = array("return_code" => "SUCCESS", "return_msg" => "等待服务商确认", "result_code" => "FAIL", "result_msg" => "等待服务商确认");

                }
            }
        }
        return $re_param;
    }

    public function machlist($param)
    {
        try {
            $Merchant = new Merchant();
            $map['id'] = ['in', $param['merchantid']];
            $list = $Merchant->where($map)->field('id,merchant')->select();
            if ($list) {
                $data['return_code'] = "SUCCESS";
                $data['return_msg'] = "SUCCESS";
                $data['result_code'] = "SUCCESS";
                $data['result_msg'] = "SUCCESS";
                $data['return_code'] = "SUCCESS";
                foreach ($list as $k => $v) {
                    $mach[$k]['merchantid'] = $v['id'];
                    $mach[$k]['merchantname'] = $v['merchant'];
                }
                $data['info'] = $mach;

            } else {
                $data = array("return_code" => "SUCCESS", "return_msg" => "SUCCESS", "result_code" => "FAIL", "result_msg" => "没有找到该门店",);
            }
        } catch (\Exception $e) {
            $data = array("return_code" => "FAIL", "return_msg" => "系统错误", "result_code" => "FAIL", "result_msg" => $e->getMessage());
        }
        return $data;
    }

    public function getmachinfo($param)
    {
        try {
            $Merchant = new Merchant();

            $map['id'] = $param['merchantid'];
            $machinfo = $Merchant->where($map)->field('id,img,merchant,agent,top_mid')->find();
            if ($machinfo) {
                $Agent = new Agent();
                $agentinfo = $Agent->where(array('id' => $machinfo['agent']))->field('name,contacts,tel,open_url')->find();
                $CardMember = new CardMember();
                $cardid = $CardMember->where(['top_mid' => $machinfo['top_mid']])->value('card_id');
                $CardQrcode = new CardQrcode();
                $qrcode_url = $CardQrcode->where(['card_id' => $cardid, 'mid' => $param['merchantid']])->value('qrcode_url');
                $re_data['mch_img'] = $machinfo['img'];
                $re_data['mch_id'] = $machinfo['id'];
                $re_data['mch_name'] = $machinfo['merchant'];
                $re_data['mch_card_url'] = $qrcode_url;
                $re_data['mch_pay_url'] = "https://" . $agentinfo['open_url'] . "/qrcode/" . $machinfo['id'] . '.png';;
                $re_data['agent_name'] = $agentinfo['name'];
                $re_data['agent_contact'] = $agentinfo['contacts'];
                $re_data['agent_tel'] = $agentinfo['tel'];
                $re_param['return_code'] = "SUCCESS";
                $re_param['return_msg'] = "SUCCESS";
                $re_param['result_code'] = "SUCCESS";
                $re_param['result_msg'] = "SUCCESS";
                $re_param['return_code'] = "SUCCESS";
                $re_param['info'] = $re_data;
            } else {
                $re_param['return_code'] = "SUCCESS";
                $re_param['return_msg'] = "SUCCESS";
                $re_param['result_code'] = "FAIL";
                $re_param['result_msg'] = "未查询到商户信息";
                $re_param['return_code'] = "";
            }
        } catch (\Exception $e) {
            $re_param['return_code'] = "FAIL";
            $re_param['return_msg'] = '系统错误';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '系统错误' . $e->getMessage();
        }


        if ($qrcode_url) {
            $rarr['code'] = 0;
            $rarr['message'] = 'SUCCESS';
            $rarr['qrcode_url'] = $qrcode_url;
        } else {
            $rarr['code'] = 9091;
            $rarr['message'] = 'ERROR';
        }
        return $re_param;

    }

    public function clientbinding($data)
    {
        try {
            $map['code'] = $data['binding_code'];
            $sdata['device_code'] = $data['device_code'];
            $sdata['status'] = 1;
            $DeviceMirco = new DeviceMicro();
            $s = $DeviceMirco->save($sdata, $map);
            if ($s) {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '绑定成功';
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '绑定码错误，请检查后重试';
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;


    }

    public function clientbindingque($param)
    {
        try {
            $map['device_code'] = $param['device_code'];
            $DeviceMirco = new DeviceMicro();
            $s = $DeviceMirco->where($map)->find();
            if ($s) {
                $Merchant = new Merchant();
                $merchant = $Merchant->where(['id' => $s['mid']])->value('merchant');
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '绑定成功';
                $rarr['merchant'] = $merchant;
                $rarr['merchantid'] = $s['mid'];
                $rarr['device_name'] = $s['device_name'];
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '没有查询到信息';
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;

    }

    public function clientupdata($param)
    {

//        $new_ver=Config::get('appconfig.version');
//        $updatalog=Config::get('appconfig.updatalog');
//        $downloadurl=Config::get('appconfig.url');
//        $filename=Config::get('appconfig.filename');
//        file_put_contents('/data2/html/osapi/updata.txt',json_encode($param),8);
//        file_put_contents('/data2/html/osapi/updata.txt',json_encode($new_ver),8);
//        if($param['client_ver']==$new_ver){
        $rarr['return_code'] = "SUCCESS";
        $rarr['return_msg'] = '';
        $rarr['result_code'] = 'FAIL';
        $rarr['result_msg'] = '没有新的版本信息';
//        }else{
//            $rarr['return_code'] = "SUCCESS";
//            $rarr['return_msg'] = '';
//            $rarr['result_code'] = 'SUCCESS';
//            $rarr['result_msg'] = '查询到新版本';
//            $rarr['new_ver']=$new_ver;
//            $rarr['updatalog']=$updatalog;
//            $rarr['downloadurl']=$downloadurl;
//            $rarr['filename']=$filename;
//        }


        return $rarr;


    }

    public function getuserlist($param)
    {
        $LoginUser = new LoginUsers();
        $Merchant = new Merchant();
        $map['id'] = $param['merchantid'];
        $mac['mid'] = array('like', '%' . trim($param['merchantid']) . '%');;
        $mab['top_mid'] = $Merchant->where($map)->value('top_mid');
        $list = $LoginUser->where($mac)->whereOr($mab)->field('username')->select();
        if ($list) {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '查询成功';
            $rarr['list'] = $list;
            $rarr['sql'] = $LoginUser->getLastSql();
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '没有查询到信息';
        }
        return $rarr;
    }

//    public function changeuser($param)
//    {
//        $LoginChange = new LoginChange();
//        if ($param['type'] == "down") {
//            $map['username'] = $param['username'];
//            $map['mid'] = $param['mid'];
//            $map['status']=1;
//            $info = $LoginChange->where($map)->order('id desc')->find();
//            if ($info) {
//                $rarr['return_code'] = "SUCCESS";
//                $rarr['return_msg'] = '';
//                $rarr['result_code'] = 'FAIL';
//                $rarr['result_msg'] = "您上次未交班，是否先进行交班";
//
//            } else {
//                $Merchant = new Merchant();
//                $data['mid'] = $param['merchantid'];
//                $data['top_mid'] = $Merchant->where('id', $param['merchantid'])->value('top_mid');
//                $data['username'] = $param['username'];
//                $data['login_time'] = $param['login_time'];
//                $data['status'] = 1;
//                $data['ip'] = $param['ip'];
//                $data['device_code'] = $param['device_code'];
//                $data['kuantai'] = $param['device_id'];
//                $LoginChange->save($data);
//                $rarr['return_code'] = "SUCCESS";
//                $rarr['return_msg'] = '';
//                $rarr['result_code'] = 'SUCCESS';
//                $rarr['result_msg'] = '记录成功';
//            }
//        }elseif($param['type'] == "up"){
//            $data['status']=2;
//            $data['login_time'] = $param['login_time'];
//            $LoginChange->save($data,['id'=>$param['changeid']]);
//            $rarr['return_code'] = "SUCCESS";
//            $rarr['return_msg'] = '';
//            $rarr['result_code'] = 'SUCCESS';
//            $rarr['result_msg'] = '记录成功';
//        }
//
//
//    }
}